package JDBC;

import java.sql.*;

/**
 * 测试批处理的基本操作
 */
public class demo5 {
    public static void main(String[] args) {
        Connection conn= null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/zz?characterEncoding=UTF-8","root","123456");

           conn.setAutoCommit(false);//把事务自动提交关闭

            stmt=conn.createStatement();
            for (int i = 0; i <20000 ; i++) {
                stmt.addBatch("INSERT INTO user (userName,age) VALUES ('zhang"+i+"',"+i+")");
            }
            stmt.executeBatch();//批处理
            conn.commit();//提交事务
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //遵循后开先开  不要在try里面合并，三个要分开写，第一个有问题，后两个会不执行
            try {
                if(rs!=null){
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if(stmt!=null){
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if(conn!=null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
